package com.chengyu.core.service.homeFloor.impl;

import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.HomeConfigMapper;
import com.chengyu.core.model.HomeConfig;
import com.chengyu.core.model.HomeConfigExample;
import com.chengyu.core.service.homeFloor.HomeFloorService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HomeFloorServiceImpl implements HomeFloorService {

    @Autowired
    private HomeConfigMapper homeConfigMapper;


    @Override
    public List<HomeConfig> listHomeFloorConfig(Integer type,Integer page, Integer pageSize) throws ServiceException {
        PageHelper.startPage(page, pageSize);

        HomeConfigExample example = new HomeConfigExample();
        example.setOrderByClause("add_time desc");
        HomeConfigExample.Criteria criteria = example.createCriteria();
        if (type != null) {
            criteria.andTypeEqualTo(type);
        }
        return homeConfigMapper.selectByExample(example);
    }

    @Override
    public CommonResult<String> editUpdate(HomeConfig homeConfig) throws ServiceException {


        if (homeConfig.getId()==null){
            //如果是广告先查看是否有
            if (homeConfig.getType()==2){
                HomeConfigExample example = new HomeConfigExample();
                example.createCriteria().andTypeEqualTo(2);
                List<HomeConfig> homeConfigs = homeConfigMapper.selectByExample(example);
                if (homeConfigs.size()>0){
                    throw new ServiceException("广告已经存在");
                }
            }

            //如果是滚动通知先查看是否有
            if (homeConfig.getType()==3){
                HomeConfigExample example2 = new HomeConfigExample();
                example2.createCriteria().andTypeEqualTo(3);
                List<HomeConfig> homeConfigs2 = homeConfigMapper.selectByExample(example2);
                if (homeConfigs2.size()>0){
                    throw new ServiceException("滚动通知内容已经存在");
                }
            }

            homeConfigMapper.insert(homeConfig);
        }else{
            homeConfigMapper.updateByPrimaryKeySelective(homeConfig);
        }

        return CommonResult.success(null);
    }

    @Override
    public CommonResult<String> del(Integer id) throws ServiceException {
        if (id==null){
            throw new ServiceException("id不能为空");
        }
        homeConfigMapper.deleteByPrimaryKey(id);
        return CommonResult.success(null);
    }

}